package com.xy.hms.config;

import com.xy.hms.model.User;
import com.xy.hms.service.UserServiceI;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author xiaye
 * @create 2020-03-12-13:51
 */
public class UserRealm extends AuthorizingRealm
{
    @Autowired
    UserServiceI userServiceI;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)
    {
        System.out.println("执行了授权====doGetAuthorizationInfo");
        //创建授权信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("room:all");
        //获取当前对象
        Subject subject = SecurityUtils.getSubject();
        //获取User对象
        User principal = (User) subject.getPrincipal();
        List<String> permissions = userServiceI.getPermission(principal.getId());
        //给登录的对象授权，授予查到的所有权限
        if(!permissions.isEmpty())
        {  //权限不为空
            for (String s : permissions)
            {
                info.addStringPermission(s);
            }
        }
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
    {
        System.out.println("执行了认证=====doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        User user = userServiceI.shiroLogin(userToken.getUsername());
        //用户名异常
        if (user==null) { return  null;  }  //抛出异常  UnknownAccountException
        //密码认证 ，shiro做~
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
